/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ChatServiceImpl.cpp. Created on: 13.10.2010 16:28:43 
 */

#include "ChatServiceImpl.hpp"
#include "ChatSessionImpl.hpp"

ChatServiceImpl::ChatServiceImpl(ISmartBus* poBus) : m_poBus(NULL), m_poEventsCallback(NULL) {
	setNewRefObject (m_poBus, poBus );
	m_poBus->getServerInstancesRegistry()->addListener(this);
}

ChatServiceImpl::~ChatServiceImpl() {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxSessions);
	SessionsType mSessionsCopy = m_mSessions;
	m_mSessions.clear();
	oLock.unlock();

	for(SessionsType::left_iterator it =  mSessionsCopy.left.begin(); it!= mSessionsCopy.left.end(); it++ ) {
		it->second->unpublish();
		it->second->release();
	}

	m_poBus->getServerInstancesRegistry()->delListener(this);

	releaseAndClear(m_poEventsCallback);
	releaseAndClear(m_poBus);
}

ChatSessionSkeleton*  ChatServiceImpl::enterToChat(const std::string& login ,  const std::string& password ,  IChatEvents* events)
		throw(IOException, SmartBusSystemException , UnableToLoginException) {
	return createChatSession(login, password, events);
}

ChatSessionSyncSkeleton* ChatServiceImpl::createChatSession( const std::string& login ,  const std::string& password , IChatEvents* events ) {
	ChatSessionSyncSkeleton* poResult = NULL;
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxSessions);
	std::string sLogin = login;
	SessionsType::left_iterator it = m_mSessions.left.find(sLogin);
	static unsigned long loginIdx = 1;
	if(it!=m_mSessions.left.end()) {
		sLogin = sLogin+"["+boost::lexical_cast<std::string> (loginIdx++)+"]";
	}
	poResult = new ChatSessionSyncSkeleton ( new ChatSessionImpl( this, sLogin, events ) );
	boost::intrusive_ptr < ChatMessage > poSysMessage ( new ChatMessage(), false );
	poSysMessage->setValue(cpputils::utils::toWideString("Connected new client: "+sLogin));
	sendSystemMessageToAll ( poSysMessage.get() );

	m_mSessions.left.insert( SessionsType::left_value_type ( sLogin, poResult ) );
	poResult->addRef();
	oLock.unlock();

	return poResult;
}

void ChatServiceImpl::onUnregisterInstance(IServerSkeleton* poInstance) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxSessions);
	bool bFound = false;
	std::string sLogin;

	SessionsType::right_iterator it = m_mSessions.right.find(poInstance);
	if(it!=m_mSessions.right.end()) {
		bFound = true;
		sLogin = it->second;
		m_mSessions.right.erase(it);
	}
	oLock.unlock();

	if(bFound) {
		poInstance->unpublish();
		poInstance->release();
		boost::intrusive_ptr < ChatMessage > poSysMessage ( new ChatMessage(), false );
		poSysMessage->setValue(cpputils::utils::toWideString("Disconnected client: "+sLogin));
		sendSystemMessageToAll ( poSysMessage.get() );
	}
}

void ChatServiceImpl::sendMessageToAll(ChatSessionImpl* poFromChatSession, ChatMessage* poMessage) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxSessions);
	for(SessionsType::left_iterator it =  m_mSessions.left.begin(); it!= m_mSessions.left.end(); it++ ) {
		ChatSessionSyncSkeleton* poSkeleton = dynamic_cast<ChatSessionSyncSkeleton*> ( it->second );
		ChatSessionImpl* poToSession = dynamic_cast<ChatSessionImpl*>  ( poSkeleton->getSyncImplementation() );
		if(poToSession!=poFromChatSession) {
			try {
				poToSession->getEvents()->onUserMessageRequest(
					poFromChatSession->getLogin(),
					poMessage,
					m_poEventsCallback
				);
			}
			catch (const SystemException& e) {
				std::cout << e.what() << std::endl;
				e.printBacktrace();
			}
		}
	}
}

void ChatServiceImpl::sendSystemMessageToAll(ChatMessage* poMessage) {
	boost::unique_lock<boost::recursive_mutex> oLock(m_mxSessions);
	for(SessionsType::left_iterator it =  m_mSessions.left.begin(); it!= m_mSessions.left.end(); it++ ) {
		ChatSessionSyncSkeleton* poSkeleton = dynamic_cast<ChatSessionSyncSkeleton*> ( it->second );
		ChatSessionImpl* poToSession = dynamic_cast<ChatSessionImpl*>  ( poSkeleton->getSyncImplementation() );
		try {
			poToSession->getEvents()->onSystemMessageRequest(
				poMessage,
				m_poEventsCallback
			);
		}
		catch (const SystemException& e) {
			std::cout << e.what() << std::endl;
			e.printBacktrace();
		}
	}
}
